﻿using AutoMapper;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using ZhiJiao.Dal;
using ZhiJiao.Models.Entities;
using ZhiJiao.Models.Entities.Enums;
using ZhiJiao.Service.Abstracts;
using ZhiJiao.Service.Dto;

namespace ZhiJiao.Service.Services
{
    /// <summary>
    /// 参与规则服务
    /// </summary>
    public class RuleService : IRuleService
    {
        private readonly BackJson _res;
        private readonly ZJDbContext _db;
        private readonly ICurrentUser _currentUser;
        private readonly IMapper _mapper;


        public RuleService(BackJson res,
                           ZJDbContext db,
                           ICurrentUser currentUser,
                           IMapper mapper)
        {
            _res = res;
            _db = db;
            _currentUser = currentUser;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取规则列表
        /// </summary>
        /// <param name="insId">机构ID</param>
        /// <param name="name">规则名称</param>
        /// <param name="type">规则类型</param>
        /// <returns></returns>
        public async Task<BackJson> GetRuleList(long insId, string? name, RuleType? type)
        {
            try
            {
                var query = _db.Rules.AsQueryable();
                query = query.Where(r=>r.Instruction.Id==insId);
                if (!string.IsNullOrEmpty(name))
                {
                    query = query.Where(r => r.Name.Contains(name));
                }
                if (type != null)
                {
                    query = query.Where(r => r.RuleType.Equals(type));
                }

                var list = query.ToList();

                _res.code = 0;
                _res.data = _mapper.Map<List<Rule>, List<RuleDto>>(list);
            }
            catch (Exception e)
            {
                _res.code = 1;
                _res.msg = e.Message;
            }
            return _res;
        }

        /// <summary>
        /// 保存参与规则
        /// </summary>
        public async Task<BackJson> Save(RuleDto dto)
        {
            try
            {
                if (dto.Id == null) // 创建
                {
                    var rule = _mapper.Map<RuleDto, Rule>(dto);
                    rule.Instruction = await _db.Instructions.FindAsync(dto.InsId);
                    await _db.Rules.AddAsync(rule);
                    await _db.SaveChangesAsync();
                    _res.code = 0;
                    _res.data = rule.Id;
                    _res.msg = "参与规则创建成功";
                }
                else // 编辑
                {
                    var rule = await _db.Rules.FirstOrDefaultAsync(r => r.Id == dto.Id);
                    if (rule != null)
                    {
                        rule.Name = dto.Name!;
                        rule.RuleType = dto.RuleType!;
                        rule.MemberLevel = dto.MemberLevel;
                        rule.WXShareCount = dto.WXShareCount;
                        rule.DYShareCount = dto.DYShareCount;
                        rule.IsActive = dto.IsActive;
                        _db.Rules.Update(rule);
                        await _db.SaveChangesAsync();
                        _res.code = 0;
                        _res.data = rule.Id;
                        _res.msg = "参与规则保存成功";
                    }
                    else
                    {
                        _res.code = 1;
                        _res.msg = "您所编辑的参与规则不存在或已被删除";
                    }
                }
            }
            catch (Exception e)
            {

                _res.code = 1;
                _res.msg = e.Message;
            }
            return _res;
        }


        /// <summary>
        /// 删除参与规则
        /// </summary>
        public async Task<BackJson> DeleteRule(long id)
        {
            try
            {
                var rule = await _db.Rules.FirstOrDefaultAsync(r => r.Id == id);
                if (rule != null)
                {
                    _db.Rules.Remove(rule);
                    await _db.SaveChangesAsync();
                    _res.code = 0;
                    _res.msg = "参与规则删除成功";
                }
                else
                {
                    _res.code = 1;
                    _res.msg = "规则不存在，或已被其他用户删除";
                }
            }
            catch (Exception e)
            {
                _res.code = 1;
                _res.msg = e.Message;
            }
            return _res;
        }

        /// <summary>
        /// 获取单个参与规则
        /// </summary>
        public async Task<BackJson> GetSingleRule(long id)
        {
            try
            {
                var rule = await _db.Rules.FirstOrDefaultAsync(r => r.Id == id);
                if (rule != null)
                {
                    _res.code = 0;
                    _res.data = _mapper.Map<Rule, RuleDto>(rule);
                }
                else
                {
                    _res.code = 1;
                    _res.msg = "您想要编辑的参与规则不存在或已被删除";
                }
            }
            catch (Exception e)
            {
                _res.code = 1;
                _res.msg = e.Message;
            }
            return _res;
        }


        /// <summary>
        ///  isActive切换
        /// </summary>
        public async Task<BackJson> IsActiveSwitch(long id, string value)
        {
            try
            {
                var rule = await _db.Rules.FirstOrDefaultAsync(r => r.Id == id);
                if (rule != null)
                {
                    if (value == "true")
                    {
                        rule.IsActive = true;
                        _res.msg = "规则已启用";
                    }
                    else
                    {
                        rule.IsActive = false;
                        _res.msg = "规则已禁用";

                    }
                    await _db.SaveChangesAsync();
                    _res.code = 0;

                }
                else
                {
                    _res.code = 1;
                    _res.msg = "参与规则不存在或已被删除";
                }
            }
            catch (Exception e)
            {
                _res.code = 1;
                _res.msg = e.Message;
            }
            return _res;
        }

        /// <summary>
        /// 获取测评规则
        /// </summary>
        public async Task<BackJson> GetEvaluationRules(long id)
        {
            var eval = await _db.Evaluations.Include(e=>e.Rules).FirstOrDefaultAsync(r=>r.Id==id);
            if (eval != null)
            {
                List<RuleDto>? list=null;
                if (eval.Rules != null && eval.Rules.Count > 0)
                {
                    list = _mapper.Map<List<Rule>, List<RuleDto>>(eval.Rules);
                }
                else
                {
                    list =new List<RuleDto>();
                }
                _res.code = 0;
                _res.data = list;
            }
            else
            {
                _res.code = 1;
                _res.msg = "编辑的测评不存在或已被删除";
            }

            return _res;
        }
    }
}
